package com.vernhe.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author VernHe
 * @date 2022年02月26日 14:29
 */
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 暴露 AuthenticationManager
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth    // 将用户名密码保存至内存中
                .inMemoryAuthentication()
                // 用户名 vernhe
                .withUser("vernhe")
                // 密码 123
                .password("{noop}123")
                // 角色
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 解决静态资源被拦截的问题
        web.ignoring().antMatchers("/asserts/**");
        web.ignoring().antMatchers("/favicon.ico");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 开启表单登录并允许访问
//                .formLogin().loginProcessingUrl("/loginSuccess").permitAll()
                // 使用Basic验证
                .httpBasic()
                // 注销的url以及注销成功后跳转的url
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/")
                // 允许访问的url
                .and().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**", "/api/**").permitAll()
                // 其余url一律都需要验证
                .anyRequest().authenticated()
                // 关闭跨域保护
                .and().csrf().disable();

    }
}
